package com.auto.survey.activity.monitoring.adapter

import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.auto.survey.R
import com.auto.survey.activity.monitoring.entity.UiPointWithCheckPoint
import com.auto.survey.util.Helper

class CollapsiblePointAdapter:Adapter<CollapsiblePointAdapter.CollapsiblePointViewHodler>() {

    private var uiPoints: List<UiPointWithCheckPoint> = emptyList()

    // 更新数据（保留展开状态）
    fun submitList(newList: List<UiPointWithCheckPoint>) {
        // 用原列表的展开状态更新新列表（避免刷新后状态丢失）
        val updatedList = newList.map { dbPoint ->
            // 查找旧列表中对应的项，保留展开状态
            val oldUiPoint = uiPoints.find { it.data.point.id == dbPoint.data.point.id }
            UiPointWithCheckPoint(
                data = dbPoint.data,
                isExpanded = oldUiPoint?.isExpanded ?: false
            )
        }
        uiPoints = newList
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CollapsiblePointViewHodler {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_point_collapsible, parent, false)
        return CollapsiblePointViewHodler(view)
    }

    override fun getItemCount(): Int  = uiPoints.size

    override fun onBindViewHolder(holder: CollapsiblePointViewHodler, position: Int) {
        holder.bind(uiPoints[position])
    }

    inner class CollapsiblePointViewHodler(itemView: View) : RecyclerView.ViewHolder(itemView){
        // 头部控件
        private val llHeader = itemView.findViewById<LinearLayout>(R.id.ll_header)
        private val ivArrow = itemView.findViewById<ImageView>(R.id.iv_arrow)

        private val point_name = itemView.findViewById<TextView>(R.id.tv_point_name)
        private val point_x = itemView.findViewById<TextView>(R.id.tv_history_check_x)
        private val point_y = itemView.findViewById<TextView>(R.id.tv_history_check_y)
        private val point_z = itemView.findViewById<TextView>(R.id.tv_history_check_z)
        private val point_hz = itemView.findViewById<TextView>(R.id.tv_history_check_hz)
        private val point_va = itemView.findViewById<TextView>(R.id.tv_history_check_va)
        private val point_sd = itemView.findViewById<TextView>(R.id.tv_history_check_sd)



        // 内容区控件
        private val llCheckpointsList = itemView.findViewById<LinearLayout>(R.id.ll_checkpoints_list)

        init {
            // 点击头部切换展开/收起状态
            llHeader.setOnClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    val item = uiPoints[position]
                    item.isExpanded = !item.isExpanded // 切换状态
                    notifyItemChanged(position) // 刷新当前Item
                }
            }
        }

        fun bind(uiPoint: UiPointWithCheckPoint) {
            val dbPoint = uiPoint.data // 原始数据库数据
            val isexpanded = uiPoint.isExpanded // UI状态

            // 1. 绑定头部（基准点信息）
            val point = dbPoint.point
            point_name.text = point.pointName
            val x = "X/北N（m）:${point.pointX}"
            val spannableStringX = SpannableString(x)
            spannableStringX.setSpan(ForegroundColorSpan("#4c4c4c".toColorInt()), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            spannableStringX.setSpan(ForegroundColorSpan("#ff669900".toColorInt()), 7, x.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            val y = "Y/东E（m）:${point.pointY}"
            val spannableStringY = SpannableString(y)
            spannableStringY.setSpan(ForegroundColorSpan("#4c4c4c".toColorInt()), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            spannableStringY.setSpan(ForegroundColorSpan("#ff669900".toColorInt()), 7, y.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            val z = "Z/高H（m）:${point.pointZ}"
            val spannableStringZ = SpannableString(z)
            spannableStringZ.setSpan(ForegroundColorSpan("#4c4c4c".toColorInt()), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            spannableStringZ.setSpan(ForegroundColorSpan("#ff669900".toColorInt()), 7, z.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            val hz = point.pointHz?.let{"水平：${Helper.radiansToDMSString(it)}（${it}）"} ?: ""
            val spannableStringHZ = SpannableString(hz)
            spannableStringHZ.setSpan(ForegroundColorSpan("#4c4c4c".toColorInt()), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            spannableStringHZ.setSpan(ForegroundColorSpan("#ff669900".toColorInt()), 3, hz.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            val va = point.pointV?.let{"竖直：${Helper.radiansToDMSString(it)}（${it}）"} ?: ""
            val spannableStringVA = SpannableString(va)
            spannableStringVA.setSpan(ForegroundColorSpan("#4c4c4c".toColorInt()), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            spannableStringVA.setSpan(ForegroundColorSpan("#ff669900".toColorInt()), 3, va.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            val sd = point.pointSD?.let{"斜距：${Helper.formateDecimal(it)}"} ?: ""
            val spannableStringSD = SpannableString(sd)
            spannableStringSD.setSpan(ForegroundColorSpan("#4c4c4c".toColorInt()), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            spannableStringSD.setSpan(ForegroundColorSpan("#ff669900".toColorInt()), 3, sd.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            point_x.text = spannableStringX
            point_y.text = spannableStringY
            point_z.text = spannableStringZ
            point_hz.text = spannableStringHZ
            point_va.text = spannableStringVA
            point_sd.text = spannableStringSD

            // 2. 处理展开/收起状态
            ivArrow.rotation = if (isexpanded) 180f else 0f // 箭头旋转动画
            llCheckpointsList.visibility = if (isexpanded) View.VISIBLE else View.GONE

            // 3. 展开时绑定检查点列表（动态添加到llCheckpointsList）
            if (isexpanded) {
                llCheckpointsList.removeAllViews() // 清空旧视图
                dbPoint.allCheckPoints.forEach {
                    // 加载检查点单行布局
                    val checkView = LayoutInflater.from(itemView.context)
                        .inflate(R.layout.item_checkpoint_row, llCheckpointsList, false)
                    // 绑定检查点数据

                    val sub_point_id = checkView.findViewById<TextView>(R.id.item_checkpoint_id)
                    val sub_point_time = checkView.findViewById<TextView>(R.id.item_checkpoint_createTime)

                    val sub_point_x = checkView.findViewById<TextView>(R.id.tv_sub_history_check_x)
                    val sub_point_y = checkView.findViewById<TextView>(R.id.tv_sub_history_check_y)
                    val sub_point_z = checkView.findViewById<TextView>(R.id.tv_sub_history_check_z)
                    val sub_point_hz = checkView.findViewById<TextView>(R.id.tv_sub_history_check_hz)
                    val sub_point_va = checkView.findViewById<TextView>(R.id.tv_sub_history_check_va)
                    val sub_point_sd = checkView.findViewById<TextView>(R.id.tv_sub_history_check_sd)

                    sub_point_id.text = "ID:${it.id}"
                    sub_point_time.text = "${it.createTime}"

                    val sub_x = "X/北N（m）:${it.checkPointX}"
                    val sub_y = "Y/东E（m）:${it.checkPointY}"
                    val sub_z = "Z/高H（m）:${it.checkPointZ}"

                    sub_point_x.text = sub_x
                    sub_point_y.text = sub_y
                    sub_point_z.text = sub_z


                    val sub_hz = "水平：${Helper.radiansToDMSString(it.checkPointHz)}（${it.checkPointHz}）"
                    val sub_va = "竖直： ${Helper.radiansToDMSString(it.checkPointV)}（${it.checkPointV}）"
                    val sub_sd = "斜距： ${Helper.formateDecimal(it.checkPointSD)}"

                    sub_point_hz.text = sub_hz
                    sub_point_va.text = sub_va
                    sub_point_sd.text = sub_sd

                    // 状态
                    llCheckpointsList.addView(checkView) // 添加到内容区
                }
            }

        }



    }


}